package com.bootdo.merchant.serivce.impl;

import static com.bootdo.common.utils.ShiroUtils.getUser;
import static com.bootdo.common.utils.ShiroUtils.getUserId;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONObject;
import com.bootdo.common.config.Constant;
import com.bootdo.common.utils.DateUtils;
import com.bootdo.common.utils.MD5Utils;
import com.bootdo.common.utils.StringUtils;
import com.bootdo.merchant.dao.AgentDao;
import com.bootdo.merchant.dao.MerchantDao;
import com.bootdo.merchant.domain.AgentDO;
import com.bootdo.merchant.domain.MerchantDO;
import com.bootdo.merchant.serivce.MerchantService;
import com.bootdo.merchant.utils.IdentUtils;
import com.bootdo.mq.RabbitUtil;
import com.bootdo.quota.dao.QuotaDao;
import com.bootdo.quota.dao.QuotaHistoryDao;
import com.bootdo.quota.domain.QuotaDO;
import com.bootdo.quota.domain.QuotaHistoryDO;
import com.bootdo.system.dao.UserDao;
import com.bootdo.system.dao.UserRoleDao;
import com.bootdo.system.domain.UserDO;
import com.bootdo.system.domain.UserRoleDO;

/**
 * @Desc 商户管理
 * @date 2019/11/14
 *
 */
@Service
public class MerchantServiceImpl implements MerchantService {

    @Autowired
    private MerchantDao merchantMapper;
    @Autowired
    private UserDao userMapper;
    @Autowired
    private UserRoleDao userRoleMapper;
    @Autowired
    private IdentUtils identUtils;
    @Autowired
    private QuotaDao quotaMapper;
    @Autowired
    private AgentDao agentMapper;
    @Autowired
    private RabbitUtil rabbitUtil;
    @Autowired
    private QuotaHistoryDao quotaHistoryMapper;

    @Override
    public MerchantDO get(Long userId){
        MerchantDO merchant = merchantMapper.get(userId);
        QuotaDO quota = quotaMapper.get(userId);
        //用户实际额度
        merchant.setBalance(quota.getActualQuota());
        return merchant;
    }

    /**
     * 获取商户代理列表
     * @param map
     * @return
     */
    @Override
    public List<MerchantDO> list(Map<String, Object> map){
        //获取用户权限
        int checkUserIsManager = userRoleMapper.checkUserIsManager(getUserId());
        if (checkUserIsManager != 1){
            map.put("userIdCreate", getUserId());
        }
        return merchantMapper.list(map);
    }

    /**
     * 获取商户代理列表总条数
     * @param map
     * @return
     */
    @Override
    public int count(Map<String, Object> map){
        return merchantMapper.count(map);
    }

    /**
     * 获取商户代理信息
     * @return
     */
    @Override
    public List<AgentDO> queryAgentMerchant(){
        Long userId = null;
        //获取用户权限
        int checkUserIsManager = userRoleMapper.checkUserIsManager(getUserId());
        if (checkUserIsManager != 1){
            userId = getUserId();
        }

        List<AgentDO> lists = new ArrayList<>();
        if (userId == null) {
            AgentDO agent = new AgentDO();
            agent.setUserId(getUserId());
            agent.setUserName(getUser().getUsername());
            lists.add(agent);
        }
        lists.addAll(agentMapper.queryAgnet(userId));
        return lists;
    }

    /**
     * 新增商户
     * @param merchant
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED,isolation = Isolation.DEFAULT,timeout=36000,rollbackFor=Exception.class)
    public int save(MerchantDO merchant){
        merchant.setUserName(merchant.getUserName().trim());
        merchant.setName(merchant.getName().trim());
        //添加用户表
        UserDO userDO = new UserDO();
        userDO.setUsername(merchant.getUserName());
        userDO.setPassword(merchant.getPassword());
        userDO.setStatus(1);
        userDO.setMobile(merchant.getMobile());
        userMapper.save(userDO);

        Long userId = userDO.getUserId();
        userRoleMapper.removeByUserId(userId);
        UserRoleDO ur = new UserRoleDO();
        ur.setUserId(userId);
        ur.setRoleId(62L);
        userRoleMapper.save(ur);

        merchant.setUserId(userId);
        merchant.setGmtCreate(new Date());
        merchant.setIdentification(identUtils.getIdentStr(16));
        merchant.setToken(StringUtils.getUUIDStr(32));
        merchant.setMoneyToken(StringUtils.getUUIDStr(32));
        merchant.setLower(0);
        int count = merchantMapper.save(merchant);

        //设置余额
        QuotaDO quota = new QuotaDO();
        quota.setUserId(userId);
        quota.setChangeReason("初始额度");
        quota.setStatus(1);
        quota.setActualQuota(0.00);
        quota.setQuota(0.00);
        quota.setChangeType(0);
        quota.setGmtDate(new Date());
        quotaMapper.save(quota);
        //插入历史表
        QuotaHistoryDO quotaHistory = new QuotaHistoryDO();
        quotaHistory.setUserId(userId);
        quotaHistory.setQuota(0.00);
        quotaHistory.setActualQuota(0.00);
        quotaHistory.setChangeReason("初始额度");
        quotaHistory.setStatus(1);
        quotaHistory.setChangeType(0);
        quotaHistory.setGmtDate(new Date());
        quotaHistory.setVersion(1);
        quotaHistoryMapper.save(quotaHistory);
        return count;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED,isolation = Isolation.DEFAULT,timeout=36000,rollbackFor=Exception.class)
    public int update(MerchantDO merchant){
        if (StringUtils.isNotBlank(merchant.getUserName())){
            merchant.setUserName(merchant.getUserName().trim());
        }
        if (StringUtils.isNotBlank(merchant.getName())){
            merchant.setName(merchant.getName().trim());
        }
        String password = merchant.getPassword();
        MerchantDO merchantDO = merchantMapper.get(merchant.getUserId());
        if (StringUtils.isBlank(password) || password.equals(merchantDO.getPassword())){
            merchant.setPassword(null);
        } else {
            merchant.setPassword(MD5Utils.encrypt(merchantDO.getUserName(), password));
            UserDO user = new UserDO();
            user.setUserId(merchant.getUserId());
            user.setPassword(merchant.getPassword());
            userMapper.update(user);
        }
        int count = merchantMapper.update(merchant);

        //修改余额
        QuotaDO quota = quotaMapper.get(merchant.getUserId());
        if (merchant.getBalance() != null && merchant.getBalance().doubleValue() != quota.getActualQuota().doubleValue()){
            String reason = "平台调整";
            //获取用户权限
            int checkUserIsManager = userRoleMapper.checkUserIsManager(getUserId());
            if (checkUserIsManager != 1){
                reason = "代理调整";
            }

            JSONObject object = new JSONObject();
            object.put("date", DateUtils.format(new Date(),DateUtils.DATE_TIME_PATTERN));
            object.put("userId", merchant.getUserId());
            object.put("money", merchant.getBalance());
            object.put("orderId", "");

            if (merchant.getBalance().doubleValue() > quota.getActualQuota().doubleValue()){
                object.put("reason", reason + "增加");
                object.put("type", 1);
            } else {
                object.put("reason", reason + "减少");
                object.put("type", 2);
            }
            rabbitUtil.sendToQueue(Constant.UPDATE_QUOTA, object.toJSONString());
        }

        return count;
    }

    /**
     * 商户状态修改
     * @param userId
     * @param status
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED,isolation = Isolation.DEFAULT,timeout=36000,rollbackFor=Exception.class)
    public int editStatus(Long userId, Integer status){
        MerchantDO merchant = merchantMapper.get(userId);
        //获取上级状态
        UserDO users = userMapper.get(merchant.getUserIdCreate());
        if (users.getStatus() == 0){
            return 0;
        }

        merchant.setGmtModified(new Date());
        merchant.setStatus(status);
        int count = merchantMapper.update(merchant);

        //修改用户状态
        UserDO user = new UserDO();
        user.setUserId(merchant.getUserId());
        user.setStatus(merchant.getStatus());
        userMapper.update(user);

        return count;
    }

    /**
     * 重置商户令牌
     * @param id
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED,isolation = Isolation.DEFAULT,timeout=36000,rollbackFor=Exception.class)
    public int resetToken(Long id){
        return userMapper.removeSecretById(id);
    }

}
